#include "ClientTcp.hpp"

int	ClientTcp::TryToWrite(std::list<Buffer *> &writeBuf,
			      int fd)
{
  return ACommunicator::TryToWrite(writeBuf, fd);
}

int	ClientTcp::TryToRead(Buffer &readBuf,
			     int fd)
{
  return ACommunicator::TryToRead(readBuf, fd);
}

int	ClientTcp::Network()
{
  int			fdMax;

  Ctl.SetVal(Control::DEFAULT);
  Tim.InitTim();
  if (CheckIsComplete(Co, FdSocket) == 0)
    return (0);
  fdMax = FdInfo.InitFdClient(FdSocket);
  if (Tcp->Select(fdMax + 1, FdInfo, Tim) == -1)
    return (-1);
  if (Tim.GetTvUsec() == 0 && Tim.GetTvSec() == 0)
    return (1);
  if (ReadOrWrite() == -1)
    return (-1);
  return (1);
}

int	ClientTcp::ReadOrWrite()
{
  if (FdInfo.FdIsset(FdSocket, FdInfo.GetReadf()))
    {
      if (TryToRead(Co.GetReadBuf(), FdSocket) == -1)
	return (-1);
    }
  else if (FdInfo.FdIsset(FdSocket, FdInfo.GetWritef()))
    {
      if (TryToWrite(Co.GetWriteBuf(), FdSocket) == -1)
	return (-1);
    }
  return (0);
}

int	ClientTcp::Connection()
{
  SockInfo	sin(Port);
  Buffer	readBuf = Co.GetReadBuf();
  
  sin.InitTcpSiCl(Machine);
  readBuf.SetBuffer(NULL);
  readBuf.SetBufferSize(0);
  readBuf.SetAlreadyRead(-1);
  if (Tcp->Connect(FdSocket, sin) == -1)
    {
      puts("Can't connect to the server.");
      return (-1);
    }
  puts("Client connected.");
  return (0);  
}

ClientTcp::ClientTcp(int		port,
		     std::string	machine)
  : ACommunicator(port),
    Machine(machine)
{
  Tcp->OpenSocket(FdSocket);
  Connection();
}

ClientTcp::~ClientTcp()
{
}

int	ClientTcp::Run()
{
  while (Network() != -1)
    if (Ctl.GetVal() == Control::BUF_COMPLETE)
      {
	puts(Ctl.GetBuf().GetBuffer());
        Co.AddListWrite((char*)"Pong", 5);
        free(Ctl.GetBuf().GetBuffer());
      }
  return 0;
}

int ClientTcp::CheckIsComplete(Connected &co,
			       int fd)
{
  return ACommunicator::CheckIsComplete(co, fd);
}

int ClientTcp::TraitementBuf()
{
  return ACommunicator::TraitementBuf();
}
